package com.example.myapplication.ui.feedback

import android.content.Context
import android.graphics.Color
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter4.BaseQuickAdapter
import com.example.myapplication.R
import com.example.myapplication.databinding.FeedbackTagBinding
import kotlin.collections.indexOfFirst
import kotlin.let

class FeedbackTagsAdapter(
    tags: MutableList<SelectableItem>,
    private val onTagSelect: (SelectableItem) -> Unit
) :
    BaseQuickAdapter<SelectableItem, FeedbackTagsAdapter.TagVH>(tags) {


    class TagVH(val viewBinding: FeedbackTagBinding) : RecyclerView.ViewHolder(viewBinding.root)


    override fun onBindViewHolder(holder: TagVH, position: Int, item: SelectableItem?) {
        item?.let {
            holder.viewBinding.tvTag.setOnClickListener {
                if (!item.isSelected) {
                    // 取消之前选中的项
                    val previousSelected = items.indexOfFirst { it.isSelected }

                    if (previousSelected != -1) {
                        items[previousSelected].isSelected = false
                        notifyItemChanged(previousSelected)
                    }
                    // 选中当前项
                    item.isSelected = true
                    notifyItemChanged(position)
                }
                onTagSelect.invoke(item)
            }
            holder.viewBinding.tvTag.text = it.tag
            if (it.isSelected){
                holder.viewBinding.tvTag.setTextColor(0xffffffff.toInt())
                holder.viewBinding.tvTag.setBackgroundResource(R.drawable.bg_channel_tag)
            }else{
                holder.viewBinding.tvTag.setTextColor(context.getColor(R.color.channel_tag_unselect))
                holder.viewBinding.tvTag.setBackgroundColor(Color.TRANSPARENT)
            }
        }
    }

    override fun onCreateViewHolder(
        context: Context,
        parent: ViewGroup,
        viewType: Int
    ): TagVH {
        val viewBinding =
            FeedbackTagBinding.inflate(LayoutInflater.from(context), parent, false)
        return TagVH(viewBinding)
    }

}

